﻿Imports TBCC.UtilityMobile
Public Class DataUploadConfigForm


    Private _pi As ProjectItem

    '选择设备的网络地址
    Private _netID As Byte = g_netID

    '起始地址
    Private Const _offset As UShort = 11   '数据上传控制参数地址

    '状态地址
    Private Const _RecordWriteOffset As UShort = 2002
    Private Const _RecordWriteLength As UShort = 1

    Private Const _BeginTimeOffset As UShort = 11
    Private Const _EndTimeOffset As UShort = 17
    Private Const _AddressInfoOffset As UShort = 2140

    Private Const _BeginTimeLength As UShort = 6
    Private Const _EndTimeLength As UShort = 6
    Private Const _AddressInfoLength As UShort = _AddressInfoInterval * 5
    Private Const _AddressInfoInterval As UShort = 30 '5个地址信息的间隔

    'Private Const _RecordIntervalOffset As UShort = 2004

    '启停状态
    Private _lRunStatus As Integer
    Private _lRunStatus4Set As Integer

    Private _Encoding As System.Text.Encoding = System.Text.Encoding.GetEncoding(936) 'gb2312

    Private _StartTime4Set As DateTime

    Private buf() As UShort
    Private byteBuf() As Byte
    Private shortBuf() As Short

    '正在修改参数标志
    Private _isModify As Boolean = False

    Private _CurSysTime As DateTime

    Private Sub DataUploadConfigForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        _pi = Me.MyParentForm.PI

        ' ClearData()

        '_lRunStatus = _pi.LocalRunStatus
        'ChangeControlStatus(_lRunStatus)
        'Me.btnOK.Enabled = True

        'Me.HideAllControl()
        If Me.MyParentForm IsNot Nothing Then
            Me.MyParentForm.SetControlEnabled(False)
        End If
        EnableModify(False)
        Me.btnCancel.Enabled = False
        Me.Timer1.Start()


    End Sub

    Private Sub DataUploadConfigForm_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        'If Me._isModify Then
        '    Me.ExitModify()
        'End If
        '   MyBase.OnClosing(e)
    End Sub

    Private Sub ClearData()
        For Each ctl As Control In Me.ActivePanel.Controls
            If ctl.GetType Is GetType(RadioButton) Then
                CType(ctl, RadioButton).Checked = False
            End If
        Next
    End Sub

    Private Sub ChangeControlStatus(ByVal lRunStatus As Integer)
        Select Case lRunStatus
            Case LocalRunStatus.Start                   '启动状态
                Me.labActive.Text = "启动"
                Me.labActive.ForeColor = Color.Green
            Case LocalRunStatus.Stop                    '停止状态
                Me.labActive.Text = "停止"              '停止RadioButton
                Me.labActive.ForeColor = Color.Red
        End Select
        _lRunStatus4Set = LocalRunStatus.Stop
        '             '启动RadioButton

        Me.pnlStartTimeSet.Enabled = False      '开始时间设置
        Me.pnlStartTimeSet.Visible = False
        Me.pnlStartTime.Enabled = False         '开始时间读取
        Me.pnlStartTime.Visible = True
        Me.pnlStopTime.Enabled = True           '停止时间设置
        Me.pnlStopTime.Visible = True

        ' Me.btnOK.Text = "停止"
        Me.dtpEndTime.Value = _CurSysTime       '结束时间设置
        If Me.MyParentForm IsNot Nothing Then
            Me.MyParentForm.SetToolsBarPrjActive(False)
        End If

        '
        '_lRunStatus4Set = LocalRunStatus.Start
        '
        '
        'Me.pnlStartTimeSet.Enabled = True       '开始时间设置
        'Me.pnlStartTimeSet.Visible = True
        'Me.pnlStartTime.Enabled = False         '开始时间读取
        'Me.pnlStartTime.Visible = False
        'Me.pnlStopTime.Enabled = False          '停止时间设置
        'Me.pnlStopTime.Visible = False
        'Me.pnlAddressInfo.Enabled = True        '地址信息设置
        'Me.btnOK.Text = "启动"
        'Me.dtpStartTimeSet.Value = _CurSysTime  '结束时间设置
        'Me.rb_time.Checked = True
        'If Me.MyParentForm IsNot Nothing Then
        '    Me.MyParentForm.SetToolsBarPrjActive(True)
        'End If


    End Sub

    ''隐藏/显示Panel中的所有控件
    'Private Sub HideAllControl()
    '    For Each ctl As Control In Me.ActivePanel.Controls
    '        ctl.Visible = False
    '        If ctl.GetType Is GetType(RadioButton) Then
    '            CType(ctl, RadioButton).Enabled = False
    '        End If
    '    Next

    '    Me.btnOK.Enabled = False
    'End Sub

    Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click

        If IsValidated() = False Then
            Exit Sub
        End If

        Dim result As Boolean = False
        Me.Cursor = Cursors.WaitCursor

        'If Me.rb_time.Checked = True Then
        '    _StartTime4Set = Me.dtpStartTimeSet.Value
        'Else
        '    If GetCurSysTime() = False Then
        '        msg.ShowError(g_strReadError)
        '        Exit Sub
        '    End If
        '    Dim ts As TimeSpan = _
        '        New TimeSpan(Me.dtpStartTimeSet.Value.Hour, Me.dtpStartTimeSet.Value.Minute, Me.dtpStartTimeSet.Value.Second)
        '    _StartTime4Set = _CurSysTime.Add(ts)
        'End If

        '开始修改变量
        'If EnterModify() = False Then
        '    Me.Cursor = Cursors.Default
        '    msg.ShowError("无法修改参数请重试。")
        '    Exit Sub
        'End If

        'EnableModify(True)

        'Me.btnOK.Enabled = False
        'Me.btnCancel.Enabled = False
        'Me.grpDataUpload.Enabled = False
        Me._isSaving = True
        result = Save()
        Me._isSaving = False
        Me.btnOK.Enabled = True
        Me.btnCancel.Enabled = True
        Me.grpDataUpload.Enabled = True

        '取消修改变量
        If ExitModify() = False Then
            Debug.Write("ExitModify错误")
        End If

        Me.Cursor = Cursors.Default

        If result Then
            'EnableModify(False)
            'Me._pi.LocalRunStatus = _lRunStatus4Set
            'If Me.MyParentForm IsNot Nothing Then
            '    Me.MyParentForm.SetControlEnabled(True)
            'End If
            msg.Show("参数保存成功。")

            If RefreshData() = True Then '重新读取数据
                EnableModify(False)
                Me._pi.LocalRunStatus = _lRunStatus
                ChangeControlStatus(_lRunStatus)
                'If _lRunStatus = LocalRunStatus.Stop Then
                '    Me.txtStartAddr.Clear() : Me.txtEndAddr.Clear()
                '    Me.txtConsigner.Clear() : Me.txtCarrier.Clear() : Me.txtConsignee.Clear()
                'End If
            End If

        Else
            msg.ShowError("参数保存失败。")
        End If

    End Sub

#Region "发送心跳包"

    '心跳包连续发送错误的次数
    Private _heartFailCount As Integer = 0

    '心跳值
    Private _heartValue As Short = 0

    '心跳值是否初始化
    Private _bheartValue As Boolean = False

    '是否正在发送心跳标志
    Private _heartSending As Boolean = False

    '是否正在保存标志
    Public _isSaving As Boolean = False

    '心跳包地址
    Private _heartIncreamentAddress As UShort = 7063

    ''' <summary>
    ''' 发送心跳包
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub HeartSend()
        If _bheartValue = False Then
            Dim b() As Short
            b = COMHelper.Instance.Send4Short(g_netID, FunctionCode.WordWritableRead, _heartIncreamentAddress, 1)
            If b IsNot Nothing AndAlso b.Length = 1 Then
                _heartValue = b(0)
                _bheartValue = True
            Else
                Exit Sub
            End If
        End If

        _heartValue = (_heartValue + 1) Mod UShort.MaxValue

        Dim result As Boolean
        result = COMHelper.Instance.Write(g_netID, FunctionCode.WordWrite, _heartIncreamentAddress, _heartValue)

        If result Then
            _heartFailCount = 0
        Else
            _heartFailCount += 1
        End If

        If _heartFailCount > 10 Then
            '提示用户可能断开连接了.
        End If

    End Sub

    ''' <summary>
    ''' 心跳定时器Tick事件
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub TimerHeart_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TimerHeart.Tick
        If Not g_HeartSend Then
            Exit Sub
        End If

        If _heartSending OrElse _isSaving Then
            Exit Sub
        End If

        _heartSending = True
        Me.HeartSend()
        _heartSending = False
    End Sub

#End Region

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Me.btnCancel.Enabled = False
        If EnterModify() = False Then
            msg.Show("无法修改参数请重试")
            Me.btnCancel.Enabled = True
            Exit Sub
        End If

        EnableModify(True)
    End Sub



    Private Sub EnableModify(ByVal value As Boolean)

        Me.btnOK.Enabled = value
        Me.btnCancel.Enabled = Not value
        Me.pnlAddressInfo.Enabled = value       '地址信息设置
        'Me.grpDataUpload.Enabled = value

        'For Each ctl As Control In Me.ActivePanel.Controls
        '    If ctl.GetType Is GetType(RadioButton) Then
        '        CType(ctl, RadioButton).Enabled = value
        '    End If
        'Next

    End Sub

    Private Function IsValidated() As Boolean
        '检测起始地
        If _lRunStatus4Set = LocalRunStatus.Start AndAlso Me.txtStartAddr.Text.Trim.Length <= 0 Then
            msg.Show("出发地不能为空。")
            Me.txtStartAddr.Focus()
            Return False
        End If

        '检测目的地
        If _lRunStatus4Set = LocalRunStatus.Start AndAlso Me.txtEndAddr.Text.Trim.Length <= 0 Then
            msg.Show("目的地不能为空。")
            Me.txtEndAddr.Focus()
            Return False
        End If

        '检测发货人
        If _lRunStatus4Set = LocalRunStatus.Start AndAlso Me.txtConsigner.Text.Trim.Length <= 0 Then
            msg.Show("发货人不能为空。")
            Me.txtConsigner.Focus()
            Return False
        End If

        '检测承运人
        If _lRunStatus4Set = LocalRunStatus.Start AndAlso Me.txtCarrier.Text.Trim.Length <= 0 Then
            msg.Show("承运人不能为空。")
            Me.txtCarrier.Focus()
            Return False
        End If

        '检测收货人
        If _lRunStatus4Set = LocalRunStatus.Start AndAlso Me.txtConsignee.Text.Trim.Length <= 0 Then
            msg.Show("收货人不能为空。")
            Me.txtConsignee.Focus()
            Return False
        End If

        Return True
    End Function

    ''' <summary>
    ''' 保存所有参数
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function Save() As Boolean

        'Select Case _lRunStatus4Set
        'Case LocalRunStatus.Start
        '    '设置启动时间
        '    If Save(_BeginTimeOffset + 0, CType(_StartTime4Set.Year - 1900, Byte)) = False Then
        '        Return False
        '    End If
        '    If Save(_BeginTimeOffset + 1, CType(_StartTime4Set.Month, Byte)) = False Then
        '        Return False
        '    End If
        '    If Save(_BeginTimeOffset + 2, CType(_StartTime4Set.Day, Byte)) = False Then
        '        Return False
        '    End If
        '    If Save(_BeginTimeOffset + 3, CType(_StartTime4Set.Hour, Byte)) = False Then
        '        Return False
        '    End If
        '    If Save(_BeginTimeOffset + 4, CType(_StartTime4Set.Minute, Byte)) = False Then
        '        Return False
        '    End If
        '    If Save(_BeginTimeOffset + 5, CType(_StartTime4Set.Second, Byte)) = False Then
        '        Return False
        '    End If

        '设置地址信息
        byteBuf = _Encoding.GetBytes(Me.txtStartAddr.Text) '出发地
        ReDim Preserve byteBuf(_AddressInfoInterval - 1)
        If Save(_AddressInfoOffset, byteBuf) = False Then
            Return False
        End If

        byteBuf = _Encoding.GetBytes(Me.txtEndAddr.Text) '目的地
        ReDim Preserve byteBuf(_AddressInfoInterval - 1)
        If Save(_AddressInfoOffset + _AddressInfoInterval * 1, byteBuf) = False Then
            Return False
        End If

        byteBuf = _Encoding.GetBytes(Me.txtConsigner.Text) '发货人
        ReDim Preserve byteBuf(_AddressInfoInterval - 1)
        If Save(_AddressInfoOffset + _AddressInfoInterval * 2, byteBuf) = False Then
            Return False
        End If

        byteBuf = _Encoding.GetBytes(Me.txtCarrier.Text) '承运人
        ReDim Preserve byteBuf(_AddressInfoInterval - 1)
        If Save(_AddressInfoOffset + _AddressInfoInterval * 3, byteBuf) = False Then
            Return False
        End If

        byteBuf = _Encoding.GetBytes(Me.txtConsignee.Text) '收货人
        ReDim Preserve byteBuf(_AddressInfoInterval - 1)
        If Save(_AddressInfoOffset + _AddressInfoInterval * 4, byteBuf) = False Then
            Return False
        End If

        '    Case LocalRunStatus.Stop
        '        '设置停止时间
        '        If Save(_EndTimeOffset + 0, CType(Me.dtpEndTime.Value.Year - 1900, Byte)) = False Then
        '            Return False
        '        End If
        '        If Save(_EndTimeOffset + 1, CType(Me.dtpEndTime.Value.Month, Byte)) = False Then
        '            Return False
        '        End If
        '        If Save(_EndTimeOffset + 2, CType(Me.dtpEndTime.Value.Day, Byte)) = False Then
        '            Return False
        '        End If
        '        If Save(_EndTimeOffset + 3, CType(Me.dtpEndTime.Value.Hour, Byte)) = False Then
        '            Return False
        '        End If
        '        If Save(_EndTimeOffset + 4, CType(Me.dtpEndTime.Value.Minute, Byte)) = False Then
        '            Return False
        '        End If
        '        If Save(_EndTimeOffset + 5, CType(Me.dtpEndTime.Value.Second, Byte)) = False Then
        '            Return False
        '        End If

        'End Select

        '设置状态
        'If Save(_RecordWriteOffset, CType(_lRunStatus4Set, UShort)) = False Then
        '    Return False
        'End If

        '设置修改使能变量
        If ParameterModifyClass.SetModifyConfirm(_netID) = False Then
            Return False
        End If

        ' Me.TimerHeart.Stop()

        Return True
    End Function

    ''' <summary>
    ''' 保存参数
    ''' </summary>
    ''' <param name="value"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function save(ByVal offset As UShort, ByVal value As UShort) As Boolean
        offset = offset + 1000
        Return COMHelper.Instance.Write(_netID, FunctionCode.WordWrite, offset, value)
    End Function

    Private Function save(ByVal offset As UShort, ByVal value As Byte) As Boolean
        offset = offset + 1000
        Return COMHelper.Instance.Write(_netID, FunctionCode.WordWrite, offset, value)
    End Function

    Private Function save(ByVal offset As UShort, ByVal value() As Byte) As Boolean
        For i As UShort = 0 To value.Length - 1
            If save(offset + i, value(i)) = False Then
                Return False
            End If
        Next
        Return True
    End Function

    ''' <summary>
    ''' 进入修改
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function EnterModify() As Boolean
        If g_test Then
            _isModify = True
            Return True
        End If

        _isModify = True

        Dim result As Boolean
        result = ParameterModifyClass.EnterModify(_netID)

        If result = False Then
            _isModify = False
            Return False
        End If

        ''开始发送心跳包
        'Me.TimerHeart.Start()

        Return True
    End Function


    ''' <summary>
    ''' 退出修改
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function ExitModify() As Boolean
        '门变量置为1
        Dim result As Boolean
        result = ParameterModifyClass.ExitModify(_netID)

        '停止发送心跳包
        Me.TimerHeart.Stop()

        If result = True Then  '修改门变量成功
            _isModify = False
        End If
        Return True
    End Function

    Private Function GetCurSysTime() As Boolean
        shortBuf = COMHelper.Instance.Send4Short(g_netID, FunctionCode.WordReadonly, 0, 7) '读1号子控时间
        If shortBuf Is Nothing OrElse shortBuf.Length < 6 Then
            Return False
        End If
        _CurSysTime = New DateTime(shortBuf(0) + 1900, shortBuf(1), shortBuf(2), shortBuf(3), shortBuf(4), shortBuf(5))

        Return True
    End Function

    Private Function RefreshData() As Boolean

        Me.Cursor = Cursors.WaitCursor

        Try
            '获取当前系统时间
            If GetCurSysTime() = False Then
                GoTo ErrorHandler
            End If

            '获取记录状态
            buf = COMHelper.Instance.Send4UShort(_netID, FunctionCode.WordWritableRead, _RecordWriteOffset, _RecordWriteLength)
            If buf Is Nothing OrElse buf.Length < _RecordWriteLength Then
                GoTo ErrorHandler
            End If
            _lRunStatus = buf(0)

            'If _lRunStatus = LocalRunStatus.Start Then
            '获取启动时间
            'shortBuf = COMHelper.Instance.Send4Short(_netID, FunctionCode.WordWritableRead, _BeginTimeOffset, _BeginTimeLength)
            'If shortBuf Is Nothing OrElse shortBuf.Length < _BeginTimeLength Then
            '    GoTo ErrorHandler
            'End If
            'Me.dtpStartTime.Value = NumericConvert.Bytes2DateTime(shortBuf, 0)
            'End If

            ''获取停止时间
            'byteBuf = COMHelper.Instance.Send4Byte(_netID, FunctionCode.WordWritableRead, _EndTimeOffset, _EndTimeLength)
            'If byteBuf Is Nothing OrElse byteBuf.Length < _EndTimeLength Then
            '    GoTo ErrorHandler
            'End If
            'Me.dtpEndTime.Value = New DateTime(byteBuf(0) + 1900, byteBuf(1), byteBuf(2), byteBuf(3), byteBuf(4), byteBuf(5))

            ' If _lRunStatus = LocalRunStatus.Start Then
            '获取地址信息
            byteBuf = COMHelper.Instance.Send4Byte2(_netID, FunctionCode.WordWritableRead, _AddressInfoOffset, _AddressInfoInterval)
            If byteBuf Is Nothing OrElse byteBuf.Length < _AddressInfoInterval Then
                GoTo ErrorHandler
            End If
            Me.txtStartAddr.Text = _Encoding.GetString(byteBuf, 0, _AddressInfoInterval)

            byteBuf = COMHelper.Instance.Send4Byte2(_netID, FunctionCode.WordWritableRead, _AddressInfoOffset + _AddressInfoInterval * 1, _AddressInfoInterval)
            If byteBuf Is Nothing OrElse byteBuf.Length < _AddressInfoInterval Then
                GoTo ErrorHandler
            End If
            Me.txtEndAddr.Text = _Encoding.GetString(byteBuf, 0, _AddressInfoInterval)

            byteBuf = COMHelper.Instance.Send4Byte2(_netID, FunctionCode.WordWritableRead, _AddressInfoOffset + _AddressInfoInterval * 2, _AddressInfoInterval)
            If byteBuf Is Nothing OrElse byteBuf.Length < _AddressInfoInterval Then
                GoTo ErrorHandler
            End If
            Me.txtConsigner.Text = _Encoding.GetString(byteBuf, 0, _AddressInfoInterval)

            byteBuf = COMHelper.Instance.Send4Byte2(_netID, FunctionCode.WordWritableRead, _AddressInfoOffset + _AddressInfoInterval * 3, _AddressInfoInterval)
            If byteBuf Is Nothing OrElse byteBuf.Length < _AddressInfoInterval Then
                GoTo ErrorHandler
            End If
            Me.txtCarrier.Text = _Encoding.GetString(byteBuf, 0, _AddressInfoInterval)

            byteBuf = COMHelper.Instance.Send4Byte2(_netID, FunctionCode.WordWritableRead, _AddressInfoOffset + _AddressInfoInterval * 4, _AddressInfoInterval)
            If byteBuf Is Nothing OrElse byteBuf.Length < _AddressInfoInterval Then
                GoTo ErrorHandler
            End If
            Me.txtConsignee.Text = _Encoding.GetString(byteBuf, 0, _AddressInfoInterval)
            '  End If

        Catch ex As Exception
            Debug.WriteLine(ex.Message)
        Finally
            Me.Cursor = Cursors.Default
        End Try

        Return True

ErrorHandler:
        msg.ShowError(g_strReadError)
        Return False

    End Function

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        Me.Timer1.Stop()
        If RefreshData() = True Then
            ' Me.btnOK.Enabled = True
            ' Me.grpDataUpload.Enabled = True
            Me._pi.LocalRunStatus = _lRunStatus
            ChangeControlStatus(_lRunStatus)
            Me.btnCancel.Enabled = True
        Else
            Me.grpDataUpload.Enabled = False
        End If
        If Me.MyParentForm IsNot Nothing Then
            Me.MyParentForm.SetControlEnabled(True)
        End If
    End Sub

    Private Sub rb_time_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rb_time.CheckedChanged
        Me.dtpStartTimeSet.CustomFormat = "yyyy-MM-dd HH:mm:ss"
        Me.dtpStartTimeSet.Value = _CurSysTime '.AddMinutes(10)
    End Sub

    Private Sub rb_delay_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rb_delay.CheckedChanged
        Me.dtpStartTimeSet.CustomFormat = "HH:mm:ss"
        Me.dtpStartTimeSet.Value = New DateTime(Now.Year, Now.Month, Now.Day, 0, 10, 0)
    End Sub

End Class